{% extends 'base.html' %}

{% block container %}
<div class="top-pad">
<h5>去更新数据库<a href="{{ url_for('cash_value.databases_list') }}">配置</a></h5>
    <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
    <link href="{{ url_for('static', filename='css/cash_value.css') }}" rel="stylesheet">
    <form method="POST" id="queryFrom">
        <br>
        <input type="text" class="form-control" placeholder="请输入保单号..." name="policy" required id="policyNum" value="500001220910"><br>
        <select class="selected form-control" name="select" id="selectEnv">
            {% for config in configs %}
            <option value="{{ config.id }}">{{ config.env }}</option>
            {% endfor %}
        </select><br>
    </form>
    <input type="button" value="查询保单信息" class="form-control"
           id="policyQuery" style="color: #edf4f6; background-color: #397094"><br>
    <div id="QueryLoading"></div>
    <div>
        <tb style="color: #491ac3">请求地址：</tb><input id="input-11" readonly class="form-control" placeholder="请求地址只能查询，不可输入...">
    </div><br>

    <div id="onePm">
        保单号：<input type="text" id="input-0" style="width: 180px">&nbsp;&nbsp;
        UUID：<span style="color: red; font-size: 20px">*</span><input type="text" id="input-1">&nbsp;&nbsp;
        保费：<span style="color: red; font-size: 20px">*</span><input type="text" id="input-2">&nbsp;&nbsp;
        保额：<span style="color: red; font-size: 20px">*</span><input type="text" id="input-3"><br>
        产品：<input type="text" id="input-4">&nbsp;&nbsp;
        性别：<input type="text" id="input-5">&nbsp;&nbsp;
        年龄：<input type="text" id="input-6">&nbsp;&nbsp;
        交费期间：<input type="text" id="input-8"><br>
        保险期间：<input type="text" id="input-9">&nbsp;&nbsp;
        领取年龄：<input type="text" id="input-10">
        <span>条款名称：</span><textarea type="text" id="input-7" rows="1" cols="50"></textarea>
    </div><br>

    <script type="text/javascript">
        // 向保单信息视图提交保单号和所选环境的ID
        $("#policyQuery").click(function () {
            let policy_num =$("#policyNum").val(); // 保单号
            let env_id = $("#selectEnv option:selected").val(); // 环境ID

            if (policy_num === ""){
                alert("保单号不能为空，请先输入保单号再查询~")
            } else {
                $.ajax({
                    url: "{{ url_for("cash_value.query_policy_info") }}",
                    type: "post",
                    dataType: "json",
                    data: {policy_num:policy_num, env_id:env_id},
                    beforeSend:function (){
                        $("#QueryLoading").html(
                            "<img src='../../static/loading/loading-4.gif' width='40'>" +
                            "<span>查询中...</span>"
                        ); //在请求后台数据之前显示loading图标
                    },
                    success:function (data) {
                        $("#QueryLoading").empty(); //ajax返回成功，清除loading图标
                        if (data.status !== 200){
                            alert(data.message)
                        }else {
                            //modifyTableContent(); // 调用函数将输入框嵌入表格
                            let res = data.message;
                            console.log(res);
                            $.each(res, function (i, obj){
                                $("#input-"+i).val(obj)
                            });
                        }
                    },
                    error:function () {alert("查询保单的Ajax请求失败了！！！")}
                });
            }
        });
    </script>


    <form method="POST" id="executeForm">
        <div>
            <span style="color: #e80e72">现价文件：</span><input type="file" name="file" id="file" value="请上传Excel文件" required>
            <tb>保单年度：</tb><input type="text" name="policyYear" id="policyYear" value="300">
            <tb>基础额度：</tb><input type="text" name="policyYear" id="baseMoney" value="1000">
            <tb>算计方式：</tb><select class="selected" name="formulaMode" id="formulaMode">
                <option value="保费">保费</option>
                <option value="保额">保额</option>
            </select>
        </div>
    </form><br>
    <input type="button" value="执行现金价值" class="form-control" id="executeCashValue"
           style="color: #edf4f6; background-color: #397094"><br>

{#    展示结果#}
    <table border="1">
        <thead>
            <tr>
                <th>保单年度</th><th>基础现价</th>
                <th>实际结果</th><th>预期结果</th><th>对比结果</th>
            </tr>
        </thead>
        <tbody id="resTbody" class="res-table-tbody res-tbody-scroll">
        </tbody>
    </table>
    <table border="1">
        <thead>
            <tr>
                <th>HTTP状态</th><th>年度对比</th><th>请求参数</th><th>请求时间</th><th>响应(异常时显示)</th>
            </tr>
        </thead>
        <tbody id="moreData" class="res-tbody-scroll res-table-tbody">
        </tbody>
    </table><br>

    <script type="text/javascript">
        // 向现价执行视图提交保单号和所选环境的ID
        $("#executeCashValue").click(function () {
            let env_name = $("#selectEnv option:selected").text(); // 环境名称
            let formula_mode = $("#formulaMode option:selected").val() // 计算方式
            let policy_year = $("#policyYear").val() // 接口返回最大年度
            let base_money = $("#baseMoney").val() // 基础额度
            let p_uuid = $("#input-1").val(); // 保单UUID
            let p_premium = $("#input-2").val(); // 保费
            let p_amount = $("#input-3").val(); // 保额
            let api_path = $("#input-11").val(); // 请求地址
            let file_input = $("#file")[0].files[0]; // 获取文件对象
            let form_data = new FormData();
            form_data.append("file_input", file_input);
            form_data.append("env_name", env_name);
            form_data.append("p_uuid", p_uuid);
            form_data.append("p_premium", p_premium);
            form_data.append("p_amount", p_amount);
            form_data.append("api_path", api_path);
            form_data.append("formula_mode", formula_mode);
            form_data.append("policy_year", policy_year);
            form_data.append("base_money", base_money);

            console.log(p_uuid + "-" + p_premium+"-"+p_amount);
            // 逻辑运算符：&&相当于and ||相当于or !相当于not
            if (typeof (file_input) == "undefined"){
                alert("请上传Excel文件~")
            } else if (p_uuid === "not fount" || p_uuid === ""){
                alert("保单UUID是必须的，请确保它不为not fount，并有值且正确！")
            } else if (p_premium === "not fount" || p_premium === ""){
                alert("保费是必须的，请确保它不为not fount，并有值且正确！")
            } else if (p_amount === "not fount" || p_amount === ""){
                alert("保额是必须的，请确保它不为not fount，并有值且正确！")
            } else{
                $.ajax({
                    url: "{{ url_for("cash_value.cash_value_execute") }}",
                    type: "post",
                    async: false,
                    data: form_data,
                    processData: false,
                    contentType: false,
                    success:function (data) {
                        if (data.status !== 200){
                            alert(data.message)
                        }else {
                            let message = data.message;
                            console.log(message);
                            let http_code = message['httpStatusMessage']['httpCode'];
                            let except = message['exceptMessage']['except'];
                            let payload = message['requestMessage']['payload'];
                            let json_response = JSON.parse(message['requestMessage']['response']); // 解析JSON字符串
                            let response = message['requestMessage']['response'];
                            let send_time = message['send_time']
                            console.log(typeof (json_response.data.policyList[0]))
                            if (json_response.data.policyList[0].status !== "200"){
                                $("#moreData").append('<tr><td>'+http_code+'</td><td>'+except+'</td><td>'+payload+'</td><td>'+send_time+'</td><td>'+response+'</td></tr>')
                                alert("执行现价时出现了异常，具体请查看第二个表格中的“响应”")
                            } else {
                                $("#moreData").append('<tr><td>'+http_code+'</td><td>'+except+'</td><td>'+payload+'</td><td>'+send_time+'</td><td></td></tr>')
                            }

                            let str = ''
                            // 输出的i和obj分别为下标与单个的对象
                            $.each(message['resultList'], function (i, obj){
                                if (obj[4] === "失败" || obj[4] === "缺少数据"){
                                    str += '<tr><td style="color: red">'+obj[0]+ '</td><td style="color: red">'+obj[1]+
                                        '</td><td style="color: red">'+obj[2]+'</td><td style="color: red">'+obj[3]+
                                        '</td><td style="color: red">'+obj[4]+'</td></tr>'
                                }else {
                                    str += '<tr><td>'+obj[0]+ '</td><td>'+obj[1]+'</td><td>'+obj[2]+
                                        '</td><td>'+obj[3]+'</td><td>'+obj[4]+'</td></tr>'
                                }
                            })
                            // 添加一个分隔行
                            str += '<tr><td style="background-color: #5e5e5e">分</td>' +
                                '<td style="background-color: #5e5e5e">隔</td>' +
                                '<td style="background-color: #5e5e5e">行</td>' +
                                '<td style="background-color: #5e5e5e">别</td>' +
                                '<td style="background-color: #5e5e5e">管</td></tr>'
                            // 添加到指定元素中
                            $("#resTbody").append(str)
                        }
                    },
                    error:function (){alert("error 500，执行现价的Ajax请求失败了！！！")}
                })
            }
        })
    </script>

</div>
{% endblock %}